#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

pthread_t **pthreads = NULL;
int *serialNumbers = NULL;
void *thread_function(void *arg)
{
    char filename[0x100];
    int value = 0;
    FILE *fp = NULL;
    if (arg)
        value = *(int *)arg;

    sprintf(filename, "%02d", value);
    strcat(filename, ".txt");

    fp = fopen(filename, "w");
    fprintf(fp, "Thread %lu started. ARG:%p. Value:%d.\t",
            pthread_self(), arg,
            value);
    fprintf(fp, "Thread %lu finished.\n", pthread_self());
    fclose(fp);
    return arg;
}

int main(int argc, const char *argv[])
{
    int thread_count = 5;
    int i;
    if (argc == 2)
    {
        printf("Trying to read number from command-line arguments...\n");
        if (sscanf(argv[1], "%d", &thread_count) != 1)
        {
            printf("Invalid number of threads.");
            printf(" Using default value of %d threads.", thread_count);
        }
    }
    else
    {
        printf("No command-line arguments provided.");
        printf(" Using default value of %d threads.", thread_count);
    }
    putchar('\n');
    pthreads = (pthread_t **)malloc(sizeof(pthread_t *) * thread_count);
    serialNumbers = (int *)malloc(thread_count * sizeof(int));
    for (i = 0; i < thread_count; i++)
    {
        serialNumbers[i] = i;
        pthreads[i] = (pthread_t *)malloc(sizeof(pthread_t));
        pthread_create(pthreads[i], NULL, thread_function, serialNumbers + i);
    }
    for (i = 0; i < thread_count; i++)
    {
        free(pthreads[i]);
    }
    free(pthreads);
    free(serialNumbers);
    return 0;
}